package com.supor.aiot.food.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.android.baseconfig.common.views.RoundImageView;
import com.bumptech.glide.Glide;
import com.supor.aiot.food.R;
import com.supor.aiot.food.bean.RecipeHotBean;

import java.util.ArrayList;
import java.util.List;

public class ImgPagerAdapter extends PagerAdapter {
    private List<RecipeHotBean> hotBeans;
    private OnImageClickListener listener;

    public void setImgClickListener(OnImageClickListener onImageClickListener){
        this.listener=onImageClickListener;
    }

    public ImgPagerAdapter(List<RecipeHotBean> hotBeans) {
        if (hotBeans.size()>1&&hotBeans.size()<4){
            this.hotBeans=new ArrayList<>();
            this.hotBeans.addAll(hotBeans);
            this.hotBeans.addAll(hotBeans);
        }else {
            this.hotBeans = hotBeans;
        }
    }

    @Override
    public int getCount() {
        return hotBeans.size() <=1 ? hotBeans.size() : Short.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view==object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        RoundImageView imageView = new RoundImageView(container.getContext());
        imageView.setRadius(container.getContext().getResources().getDimension(R.dimen.dp_10));
        imageView.setOnlyUp(true);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        Glide.with(container.getContext()).load(hotBeans.get(position%hotBeans.size()).getSmallVertical()).into(imageView);
        container.addView(imageView);
        imageView.setOnClickListener(view -> {
            if (listener!=null)listener.onImgClicked(position%hotBeans.size());
        });
        return imageView;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
       container.removeView((View) object);
    }


    public interface OnImageClickListener {
        void onImgClicked(int position);
    }
}
